import threading
import json
import random
import time
from filelock import FileLock

# 定义数据库类
class Database:
    def __init__(self, filename):
        self.filename = filename
        self.lock = threading.Lock()
        self.filelock = FileLock(filename + '.lock')
        self.data = self.load_data()

    # 读取数据
    def load_data(self):
        with self.lock:
            try:
                with open(self.filename, "r") as f:
                    return json.load(f)
            except:
                return {}

    # 写入数据
    def save_data(self):
        with self.filelock:
            with open(self.filename, "w") as f:
                json.dump(self.data, f)


    # 查询数据
    def query(self, key):
        with self.lock:
            return self.data.get(key)

    # 查询长度
    def length(self):
        with self.lock:
            return len(self.data)
        
    # 随机取出一个
    def pop(self):
        with self.lock:
            r_key = random.choice(list(self.data.keys()))
            r_value = self.data[r_key]
        self.delete(r_key)
        return r_value
            
    # 插入数据
    def insert(self, key, value):
        with self.lock:
            self.data[key] = value
            self.save_data()
        return
    
    # 批量插入数据
    def insertBunch(self,items):
        with self.lock:
            for (key,value) in items.items():
                self.data[key] = value
            self.save_data()
        return

    # 更新数据
    def update(self, key, value):
        with self.lock:
            if key in self.data:
                self.data[key] = value
                self.save_data()

    # 删除数据
    def delete(self, key):
        with self.lock:
            if key in self.data:
                del self.data[key]
                self.save_data()

    # 查重
    def check(self,key):
        if key in self.data:
            return True
        else:
            return False